home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / 20 adonet connected / adonet connected / connectedadonetform.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  31.5 KB  |  833 lines

  1. Imports System.Data
  2. Imports System.Data.OleDb
  3. Imports System.Data.SqlClient
  4.  
  5. Public Class ConnectedAdonetForm
  6.     Inherits System.Windows.Forms.Form
  7.  
  8. #Region " Windows Form Designer generated code "
  9.  
  10.     Public Sub New()
  11.         MyBase.New()
  12.  
  13.         'This call is required by the Windows Form Designer.
  14.         InitializeComponent()
  15.  
  16.         'Add any initialization after the InitializeComponent() call
  17.  
  18.     End Sub
  19.  
  20.     'Form overrides dispose to clean up the component list.
  21.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
  22.         If disposing Then
  23.             If Not (components Is Nothing) Then
  24.                 components.Dispose()
  25.             End If
  26.         End If
  27.         MyBase.Dispose(disposing)
  28.     End Sub
  29.     Friend WithEvents btnOpen As System.Windows.Forms.Button
  30.     Friend WithEvents btnAsynchronous As System.Windows.Forms.Button
  31.     Friend WithEvents lblStatus As System.Windows.Forms.Label
  32.     Friend WithEvents btnNestedTrans As System.Windows.Forms.Button
  33.     Friend WithEvents btnNamedTrans As System.Windows.Forms.Button
  34.     Friend WithEvents btnActionCommand As System.Windows.Forms.Button
  35.     Friend WithEvents btnQuery As System.Windows.Forms.Button
  36.     Friend WithEvents txtOut As System.Windows.Forms.TextBox
  37.     Friend WithEvents btnExecuteScalar As System.Windows.Forms.Button
  38.     Friend WithEvents btnExecuteXmlReader As System.Windows.Forms.Button
  39.     Friend WithEvents btnGetValues As System.Windows.Forms.Button
  40.     Friend WithEvents btnMultipleResultsets As System.Windows.Forms.Button
  41.     Friend WithEvents btnErrors As System.Windows.Forms.Button
  42.     Friend WithEvents btnStoredProc As System.Windows.Forms.Button
  43.     Friend WithEvents btnParamCommand As System.Windows.Forms.Button
  44.  
  45.     'Required by the Windows Form Designer
  46.     Private components As System.ComponentModel.Container
  47.  
  48.     'NOTE: The following procedure is required by the Windows Form Designer
  49.     'It can be modified using the Windows Form Designer.  
  50.     'Do not modify it using the code editor.
  51.     Friend WithEvents btnDeriveParams As System.Windows.Forms.Button
  52.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  53.         Me.btnMultipleResultsets = New System.Windows.Forms.Button()
  54.         Me.btnActionCommand = New System.Windows.Forms.Button()
  55.         Me.txtOut = New System.Windows.Forms.TextBox()
  56.         Me.btnStoredProc = New System.Windows.Forms.Button()
  57.         Me.btnQuery = New System.Windows.Forms.Button()
  58.         Me.btnNestedTrans = New System.Windows.Forms.Button()
  59.         Me.btnExecuteScalar = New System.Windows.Forms.Button()
  60.         Me.btnExecuteXmlReader = New System.Windows.Forms.Button()
  61.         Me.btnErrors = New System.Windows.Forms.Button()
  62.         Me.lblStatus = New System.Windows.Forms.Label()
  63.         Me.btnOpen = New System.Windows.Forms.Button()
  64.         Me.btnAsynchronous = New System.Windows.Forms.Button()
  65.         Me.btnParamCommand = New System.Windows.Forms.Button()
  66.         Me.btnNamedTrans = New System.Windows.Forms.Button()
  67.         Me.btnGetValues = New System.Windows.Forms.Button()
  68.         Me.btnDeriveParams = New System.Windows.Forms.Button()
  69.         Me.SuspendLayout()
  70.         '
  71.         'btnMultipleResultsets
  72.         '
  73.         Me.btnMultipleResultsets.Location = New System.Drawing.Point(160, 304)
  74.         Me.btnMultipleResultsets.Name = "btnMultipleResultsets"
  75.         Me.btnMultipleResultsets.Size = New System.Drawing.Size(128, 40)
  76.         Me.btnMultipleResultsets.TabIndex = 0
  77.         Me.btnMultipleResultsets.Text = "Multiple Resultsets"
  78.         '
  79.         'btnActionCommand
  80.         '
  81.         Me.btnActionCommand.Location = New System.Drawing.Point(24, 256)
  82.         Me.btnActionCommand.Name = "btnActionCommand"
  83.         Me.btnActionCommand.Size = New System.Drawing.Size(128, 40)
  84.         Me.btnActionCommand.TabIndex = 0
  85.         Me.btnActionCommand.Text = "Action Command"
  86.         '
  87.         'txtOut
  88.         '
  89.         Me.txtOut.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
  90.                     Or System.Windows.Forms.AnchorStyles.Left) _
  91.                     Or System.Windows.Forms.AnchorStyles.Right)
  92.         Me.txtOut.Location = New System.Drawing.Point(312, 16)
  93.         Me.txtOut.Multiline = True
  94.         Me.txtOut.Name = "txtOut"
  95.         Me.txtOut.ScrollBars = System.Windows.Forms.ScrollBars.Both
  96.         Me.txtOut.Size = New System.Drawing.Size(320, 328)
  97.         Me.txtOut.TabIndex = 2
  98.         Me.txtOut.Text = ""
  99.         Me.txtOut.WordWrap = False
  100.         '
  101.         'btnStoredProc
  102.         '
  103.         Me.btnStoredProc.Location = New System.Drawing.Point(160, 208)
  104.         Me.btnStoredProc.Name = "btnStoredProc"
  105.         Me.btnStoredProc.Size = New System.Drawing.Size(128, 40)
  106.         Me.btnStoredProc.TabIndex = 0
  107.         Me.btnStoredProc.Text = "Stored Procedures"
  108.         '
  109.         'btnQuery
  110.         '
  111.         Me.btnQuery.Location = New System.Drawing.Point(24, 304)
  112.         Me.btnQuery.Name = "btnQuery"
  113.         Me.btnQuery.Size = New System.Drawing.Size(128, 40)
  114.         Me.btnQuery.TabIndex = 0
  115.         Me.btnQuery.Text = "Query Command"
  116.         '
  117.         'btnNestedTrans
  118.         '
  119.         Me.btnNestedTrans.Location = New System.Drawing.Point(24, 160)
  120.         Me.btnNestedTrans.Name = "btnNestedTrans"
  121.         Me.btnNestedTrans.Size = New System.Drawing.Size(128, 40)
  122.         Me.btnNestedTrans.TabIndex = 0
  123.         Me.btnNestedTrans.Text = "Nested Transactions"
  124.         '
  125.         'btnExecuteScalar
  126.         '
  127.         Me.btnExecuteScalar.Location = New System.Drawing.Point(160, 64)
  128.         Me.btnExecuteScalar.Name = "btnExecuteScalar"
  129.         Me.btnExecuteScalar.Size = New System.Drawing.Size(128, 40)
  130.         Me.btnExecuteScalar.TabIndex = 0
  131.         Me.btnExecuteScalar.Text = "ExecuteScalar"
  132.         '
  133.         'btnExecuteXmlReader
  134.         '
  135.         Me.btnExecuteXmlReader.Location = New System.Drawing.Point(160, 112)
  136.         Me.btnExecuteXmlReader.Name = "btnExecuteXmlReader"
  137.         Me.btnExecuteXmlReader.Size = New System.Drawing.Size(128, 40)
  138.         Me.btnExecuteXmlReader.TabIndex = 0
  139.         Me.btnExecuteXmlReader.Text = "ExecuteXmlReader"
  140.         '
  141.         'btnErrors
  142.         '
  143.         Me.btnErrors.Location = New System.Drawing.Point(24, 64)
  144.         Me.btnErrors.Name = "btnErrors"
  145.         Me.btnErrors.Size = New System.Drawing.Size(128, 40)
  146.         Me.btnErrors.TabIndex = 0
  147.         Me.btnErrors.Text = "Errors collection"
  148.         '
  149.         'lblStatus
  150.         '
  151.         Me.lblStatus.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
  152.         Me.lblStatus.Dock = System.Windows.Forms.DockStyle.Bottom
  153.         Me.lblStatus.Location = New System.Drawing.Point(0, 357)
  154.         Me.lblStatus.Name = "lblStatus"
  155.         Me.lblStatus.Size = New System.Drawing.Size(648, 24)
  156.         Me.lblStatus.TabIndex = 1
  157.         '
  158.         'btnOpen
  159.         '
  160.         Me.btnOpen.Location = New System.Drawing.Point(24, 16)
  161.         Me.btnOpen.Name = "btnOpen"
  162.         Me.btnOpen.Size = New System.Drawing.Size(128, 40)
  163.         Me.btnOpen.TabIndex = 0
  164.         Me.btnOpen.Text = "Open the connection"
  165.         '
  166.         'btnAsynchronous
  167.         '
  168.         Me.btnAsynchronous.Location = New System.Drawing.Point(24, 112)
  169.         Me.btnAsynchronous.Name = "btnAsynchronous"
  170.         Me.btnAsynchronous.Size = New System.Drawing.Size(128, 40)
  171.         Me.btnAsynchronous.TabIndex = 0
  172.         Me.btnAsynchronous.Text = "Asynchronous Open"
  173.         '
  174.         'btnParamCommand
  175.         '
  176.         Me.btnParamCommand.Location = New System.Drawing.Point(160, 160)
  177.         Me.btnParamCommand.Name = "btnParamCommand"
  178.         Me.btnParamCommand.Size = New System.Drawing.Size(128, 40)
  179.         Me.btnParamCommand.TabIndex = 0
  180.         Me.btnParamCommand.Text = "Parameterized Command"
  181.         '
  182.         'btnNamedTrans
  183.         '
  184.         Me.btnNamedTrans.Location = New System.Drawing.Point(24, 208)
  185.         Me.btnNamedTrans.Name = "btnNamedTrans"
  186.         Me.btnNamedTrans.Size = New System.Drawing.Size(128, 40)
  187.         Me.btnNamedTrans.TabIndex = 0
  188.         Me.btnNamedTrans.Text = "Named Transactions"
  189.         '
  190.         'btnGetValues
  191.         '
  192.         Me.btnGetValues.Location = New System.Drawing.Point(160, 16)
  193.         Me.btnGetValues.Name = "btnGetValues"
  194.         Me.btnGetValues.Size = New System.Drawing.Size(128, 40)
  195.         Me.btnGetValues.TabIndex = 0
  196.         Me.btnGetValues.Text = "the GetValues method"
  197.         '
  198.         'btnDeriveParams
  199.         '
  200.         Me.btnDeriveParams.Location = New System.Drawing.Point(160, 256)
  201.         Me.btnDeriveParams.Name = "btnDeriveParams"
  202.         Me.btnDeriveParams.Size = New System.Drawing.Size(128, 40)
  203.         Me.btnDeriveParams.TabIndex = 3
  204.         Me.btnDeriveParams.Text = "DeriveParameters method"
  205.         '
  206.         'ConnectedAdonetForm
  207.         '
  208.         Me.AutoScaleBaseSize = New System.Drawing.Size(7, 17)
  209.         Me.ClientSize = New System.Drawing.Size(648, 381)
  210.         Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnDeriveParams, Me.btnParamCommand, Me.btnStoredProc, Me.btnErrors, Me.btnMultipleResultsets, Me.btnGetValues, Me.btnExecuteXmlReader, Me.btnExecuteScalar, Me.txtOut, Me.btnQuery, Me.btnActionCommand, Me.btnNamedTrans, Me.btnNestedTrans, Me.lblStatus, Me.btnAsynchronous, Me.btnOpen})
  211.         Me.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
  212.         Me.Name = "ConnectedAdonetForm"
  213.         Me.Text = "ADO.NET Demo"
  214.         Me.ResumeLayout(False)
  215.  
  216.     End Sub
  217.  
  218. #End Region
  219.  
  220.     ' ensure that only one of these three constants is true
  221. #Const OLEDBBIBLIO = -1
  222. #Const OLEDBPUBS = 0
  223. #Const SQLPUBS = 0
  224.  
  225.     ' open the connection - must be the first step
  226.  
  227.     Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
  228.  
  229. #If OLEDBBIBLIO Then
  230.         Dim cn As New OleDbConnection(BiblioConnString)
  231. #ElseIf OLEDBPUBS Then
  232.         Dim cn As New OleDbConnection(OledbPubsConnString )
  233. #ElseIf SQLPUBS Then
  234.         Dim cn As New SqlConnection(SqlPubsConnString)
  235. #End If
  236.         AddHandler cn.StateChange, AddressOf cn_StateChange
  237.  
  238.         Try
  239.             cn.Open()
  240.             ' process the data here.
  241.             ' ...
  242.         Catch ex As Exception
  243.             MessageBox.Show(ex.Message)
  244.         Finally
  245.             ' Close the connection whather it happens.
  246.             cn.Close()
  247.         End Try
  248.     End Sub
  249.  
  250.     ' this event fires when the connection is opened or closed
  251.  
  252.     Private Sub cn_StateChange(ByVal sender As Object, ByVal e As System.Data.StateChangeEventArgs)
  253.         ' Show the status of the connection in a Label control.
  254.         If (e.CurrentState And ConnectionState.Open) <> 0 Then
  255.             lblStatus.Text = "The connection has been opened"
  256.         ElseIf e.CurrentState = ConnectionState.Closed Then
  257.             lblStatus.Text = "The connection has been closed"
  258.         End If
  259.     End Sub
  260.  
  261.     ' list errors
  262.  
  263.     Private Sub btnErrors_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnErrors.Click
  264.  
  265. #If OLEDBBIBLIO Then
  266.         Dim cn As New OleDbConnection(BiblioConnString)
  267.         Dim cmd As New OleDbCommand("UPDATE xyz SET id=1", cn)
  268. #ElseIf OLEDBPUBS Then
  269.         Dim cn As New OleDbConnection(OledbPubsConnString )
  270.         Dim cmd As New OleDbCommand("UPDATE xyz SET id=1", cn)
  271. #ElseIf SQLPUBS Then
  272.         Dim cn As New SqlConnection(SqlPubsConnString)
  273.         Dim cmd As New SqlCommand("UPDATE xyz SET id=1", cn)
  274. #End If
  275.  
  276.         Try
  277.             cn.Open()
  278.             ' Run a query that references a table that doesn't exist.
  279.             cmd.ExecuteNonQuery()
  280.  
  281. #If OLEDBBIBLIO Or OLEDBPUBS Then
  282.         Catch ex As OleDbException
  283.             ' An OleDbException has occurred - display details
  284.             Dim i As Integer, msg As String
  285.             For i = 0 To ex.errors.Count - 1
  286.                 Dim er As OleDbError = ex.Errors(i)
  287.                 msg = "Message = " & er.Message & ControlChars.CrLf
  288.                 msg &= "Source = " & er.Source & ControlChars.CrLf
  289.                 msg &= "NativeError = " & er.NativeError & ControlChars.CrLf
  290.                 msg &= "SQLState = " & er.SQLState & ControlChars.CrLf
  291.             Next
  292.             txtOut.Text = msg
  293. #Else
  294.         Catch ex As SqlException
  295.             ' An SqlException has occurred - display details
  296.             Dim i As Integer, msg As String
  297.             For i = 0 To ex.errors.Count - 1
  298.                 Dim er As SqlError = ex.Errors(i)
  299.                 msg = "Message = " & er.Message & ControlChars.CrLf
  300.                 msg &= "Source = " & er.Source & ControlChars.CrLf
  301.                 msg &= "State = " & er.State & ControlChars.CrLf
  302.                 msg &= "Server = " & er.Server & ControlChars.CrLf
  303.             Next
  304.             txtOut.Text = msg
  305. #End If
  306.  
  307.         Catch ex As Exception
  308.             ' A generic expection has occurred.
  309.             txtOut.Text = ex.Message
  310.         End Try
  311.  
  312.     End Sub
  313.  
  314.     Delegate Sub OpenMethod()
  315.  
  316.     ' demonstrates asynchronous calls
  317.  
  318.     Private Sub btnAsynchronous_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAsynchronous.Click
  319.  
  320. #If OLEDBBIBLIO Then
  321.         Dim cn As New OleDbConnection(BiblioConnString)
  322. #ElseIf OLEDBPUBS Then
  323.         Dim cn As New OleDbConnection(OledbPubsConnString )
  324. #ElseIf SQLPUBS Then
  325.         Dim cn As New SqlConnection(SqlPubsConnString)
  326. #End If
  327.  
  328.         ' Create a delegate that points to it.
  329.         Dim asyncOpen As New OpenMethod(AddressOf cn.Open)
  330.         ' Open it asynchronously - pass the delegate as the cookie.
  331.         Dim ar As IAsyncResult = asyncOpen.BeginInvoke(AddressOf OpenComplete, asyncOpen)
  332.         ' Do something else here.
  333.         ' ...
  334.         lblStatus.Text = "Waiting ..."
  335.     End Sub
  336.  
  337.     ' this method is called when the Open operation is completed
  338.  
  339.     Sub OpenComplete(ByVal ar As IAsyncResult)
  340.         ' retrieve a reference to the delegate.
  341.         Dim asyncOpen As OpenMethod = CType(ar.AsyncState, OpenMethod)
  342.  
  343.         Try
  344.             ' Complete the operation.
  345.             asyncOpen.EndInvoke(ar)
  346.             lblStatus.Text = "The connection has been opened"
  347.         Catch ex As Exception
  348.             MessageBox.Show(ex.Message)
  349.         End Try
  350.     End Sub
  351.  
  352.     ' demonstrates nested transactions (Access only)
  353.  
  354.     Private Sub btnNestedTrans_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNestedTrans.Click
  355.         ' This works only with Access databases.
  356.         Dim cn As New OleDbConnection(BiblioConnString)
  357.         Try
  358.             cn.Open()
  359.             ' Open the first transaction
  360.             Dim tr As OleDbTransaction = cn.BeginTransaction(IsolationLevel.ReadCommitted)
  361.             ' Open a nested transaction 
  362.             Dim tr2 As OleDbTransaction = tr.Begin(IsolationLevel.ReadUncommitted)
  363.             ' ...
  364.             ' Rollback the inner transaction.
  365.             tr2.Rollback()
  366.  
  367.             ' Commit the outer transaction.
  368.             tr.Commit()
  369.         Catch ex As Exception
  370.             Debug.WriteLine(ex.Message)
  371.         Finally
  372.             cn.Close()
  373.         End Try
  374.     End Sub
  375.  
  376.     ' demonstrates named SQL Server transactions
  377.  
  378.     Private Sub btnNamedTrans_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNamedTrans.Click
  379.         ' This only works with the SQL Server provider
  380.         Dim cn As New SqlConnection(SqlPubsConnString)
  381.  
  382.         Try
  383.             cn.Open()
  384.  
  385.             ' Open a named transaction
  386.             Dim tr As SqlTransaction = cn.BeginTransaction(IsolationLevel.ReadCommitted, "MainTran")
  387.             ' create a savepoint
  388.             tr.Save("EndOfFirstPart")
  389.  
  390.             ' ...
  391.             ' Rollback the inner transaction.
  392.             tr.Rollback("EndOfFirstPart")
  393.  
  394.             ' Commit the outer transaction.
  395.             tr.Commit()
  396.         Catch ex As Exception
  397.             Debug.WriteLine(ex.Message)
  398.         Finally
  399.             cn.Close()
  400.         End Try
  401.     End Sub
  402.  
  403.     ' perform an action SQL command
  404.  
  405.     Private Sub btnActionCommand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnActionCommand.Click
  406.  
  407. #If OLEDBBIBLIO Then
  408.         Dim cn As New OleDbConnection(BiblioConnString)
  409.         Dim tr As OleDbTransaction
  410.         Dim sql As String = "INSERT INTO Authors (Author, [Year Born]) VALUES ('Joe Doe', 1955)"
  411.         Dim cmd As OleDbCommand
  412. #ElseIf OLEDBPUBS Then
  413.         Dim cn As New OleDbConnection(OledbPubsConnString )
  414.         Dim tr As OleDbTransaction
  415.         Dim cmd As OleDbCommand
  416.         Dim sql as String = "INSERT Authors (au_lname, au_fname, phone, address, city, state, zip, contract) " _
  417.             & "VALUES ('Doe', 'Joe', '123-123-1234', '9999 Street', 'San Francisco', 'CA', -1)"
  418. #ElseIf SQLPUBS Then
  419.         Dim cn As New SqlConnection(SqlPubsConnString)
  420.         Dim tr As SqlTransaction
  421.         Dim cmd As SqlCommand
  422.         Dim sql as String = "INSERT Authors (au_lname, au_fname, phone, address, city, state, zip, contract) " _
  423.             & "VALUES ('Doe', 'Joe', '123-123-1234', '9999 Street', 'San Francisco', 'CA', -1)"
  424. #End If
  425.         Try
  426.             ' Open a connection.
  427.             cn.Open()
  428.             ' Open a transaction.
  429.             tr = cn.BeginTransaction()
  430.  
  431.             ' Create an action command on that connection.
  432.             cmd = cn.CreateCommand()
  433.             cmd.CommandText = sql
  434.             cmd.Transaction = tr
  435.  
  436.             ' Run the query, get the number of affected records.
  437.             Dim records As Integer = cmd.ExecuteNonQuery()
  438.             Debug.WriteLine(records)                      ' => 1
  439.  
  440.             ' Commit the transaction
  441.             tr.Commit()
  442.  
  443.         Catch ex As OleDbException
  444.             Debug.WriteLine(ex.Message)
  445.         Finally
  446.             ' Close the connection.
  447.             cn.Close()
  448.         End Try
  449.     End Sub
  450.  
  451.     ' perform a query SQL command
  452.  
  453.     Private Sub btnQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuery.Click
  454.  
  455.         ' Define the command to read the Publishers table
  456.         Dim sql As String = "SELECT * FROM Publishers"
  457.  
  458. #If OLEDBBIBLIO Then
  459.         Dim cn As New OleDbConnection(BiblioConnString)
  460.         Dim cmd As New OleDbCommand(sql, cn)
  461.         Dim dr As OleDbDataReader
  462. #ElseIf OLEDBPUBS Then
  463.         DIm cn as New OleDbConnection(OledbPubsConnString)
  464.         Dim cmd As New OleDbCommand(sql, cn)
  465.         Dim dr As OleDbDataReader 
  466. #ElseIf SQLPUBS Then
  467.         DIm cn as New SqlConnection(SqlPubsConnString)
  468.         Dim cmd As New SqlCommand(sql, cn)
  469.         Dim dr As SqlDataReader 
  470. #End If
  471.  
  472.         Try
  473.             ' Open a connection.
  474.             cn.Open()
  475.             dr = cmd.ExecuteReader()
  476.  
  477.             ' Display all fields
  478.             Do While dr.Read
  479.                 Dim res As String = ""
  480.                 Dim i As Integer
  481.                 ' Iterate over all fields.
  482.                 For i = 0 To dr.FieldCount - 1
  483.                     ' Insert a comma if necessary.
  484.                     If res.Length > 0 Then res &= ", "
  485.                     ' Append field name and value.
  486.                     res &= dr.GetName(i) & "="
  487.                     If dr.IsDBNull(i) Then
  488.                         res &= "<NULL>"
  489.                     Else
  490.                         res &= dr.GetValue(i).ToString
  491.                     End If
  492.                 Next
  493.                 ' Append to the result textbox.
  494.                 txtOut.AppendText(res & ControlChars.CrLf)
  495.             Loop
  496.             dr.Close()
  497.  
  498.         Catch ex As OleDbException
  499.             Debug.WriteLine(ex.Message)
  500.         Finally
  501.             ' Close the connection.
  502.             cn.Close()
  503.         End Try
  504.  
  505.     End Sub
  506.  
  507.     ' display values from a query
  508.  
  509.     Private Sub btnGetValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetValues.Click
  510.  
  511.         ' Define the command to read the Publishers table
  512.         Dim sql As String = "SELECT * FROM Publishers"
  513.  
  514. #If OLEDBBIBLIO Then
  515.         Dim cn As New OleDbConnection(BiblioConnString)
  516.         Dim cmd As New OleDbCommand(sql, cn)
  517.         Dim dr As OleDbDataReader
  518. #ElseIf OLEDBPUBS Then
  519.         DIm cn as New OleDbConnection(OledbPubsConnString)
  520.         Dim cmd As New OleDbCommand(sql, cn)
  521.         Dim dr As OleDbDataReader
  522. #ElseIf SQLPUBS Then
  523.         DIm cn as New SqlConnection(SqlPubsConnString)
  524.         Dim cmd As New SqlCommand(sql, cn)
  525.         Dim dr As SqlDataReader 
  526. #End If
  527.  
  528.         Try
  529.             ' Open a connection.
  530.             cn.Open()
  531.             ' Read data into the DataReader
  532.             dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
  533.  
  534.             ' Build the array of all fields.
  535.             Dim fldNames(dr.FieldCount - 1) As String
  536.             Dim i As Integer
  537.             For i = 0 To dr.FieldCount - 1
  538.                 fldNames(i) = dr.GetName(i)
  539.             Next
  540.  
  541.             ' Display all fields
  542.             Do While dr.Read
  543.                 Dim res As New System.Text.StringBuilder(256)
  544.                 ' Get all the values in one shot.
  545.                 Dim values(dr.FieldCount - 1) As Object
  546.                 dr.GetValues(values)
  547.  
  548.                 ' Iterate over all fields.
  549.                 For i = 0 To dr.FieldCount - 1
  550.                     ' Insert a comma if necessary.
  551.                     If res.Length > 0 Then res.Append(", ")
  552.                     ' Append field name and equal sign.
  553.                     res.Append(fldNames(i))
  554.                     res.Append("=")
  555.                     ' Append the field value, or <NULL>.
  556.                     If IsDBNull(values(i)) Then
  557.                         res.Append("<NULL>")
  558.                     Else
  559.                         res.Append(values(i).ToString)
  560.                     End If
  561.                 Next
  562.                 ' Append to the result textbox.
  563.                 res.Append(ControlChars.CrLf)
  564.                 txtOut.AppendText(res.ToString)
  565.             Loop
  566.  
  567.         Catch ex As OleDbException
  568.             Debug.WriteLine(ex.Message)
  569.         Finally
  570.             ' Close the DataReader and the Connection
  571.             dr.Close()
  572.         End Try
  573.     End Sub
  574.  
  575.     ' demonstrates the ExecuteScalar method
  576.  
  577.     Private Sub btnExecuteScalar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExecuteScalar.Click
  578.         ' Define the command to read a single scalar value
  579.  
  580. #If OLEDBBIBLIO Then
  581.         Dim cn As New OleDbConnection(BiblioConnString)
  582.         Dim sql As String = "SELECT Name FROM Publishers WHERE PubID=1"
  583.         Dim cmd As New OleDbCommand(sql, cn)
  584. #ElseIf OLEDBPUBS Then
  585.         DIm cn as New OleDbConnection(OledbPubsConnString)
  586.         Dim sql As String = "SELECT Name FROM Publishers WHERE pub_ID=1"
  587.         Dim cmd As New OleDbCommand(sql, cn)
  588. #ElseIf SQLPUBS Then
  589.         DIm cn as New SqlConnection(SqlPubsConnString)
  590.         Dim sql As String = "SELECT Name FROM Publishers WHERE pub_id=1"
  591.         Dim cmd As New SqlCommand(sql, cn)
  592. #End If
  593.  
  594.         Try
  595.             ' Open a connection.
  596.             cn.Open()
  597.  
  598.             ' Read the value.
  599.             txtOut.Text = cmd.ExecuteScalar().ToString
  600.         Catch ex As OleDbException
  601.             Debug.WriteLine(ex.Message)
  602.  
  603.         Finally
  604.             ' Close the connection.
  605.             cn.Close()
  606.         End Try
  607.     End Sub
  608.  
  609.     ' demonstrates the ExecuteXmlReader method (SQL Server only)
  610.  
  611.     Private Sub btnExecuteXmlReader_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExecuteXmlReader.Click
  612.         ' Open a connection to SQL Server 2000.
  613.         Dim cn As New SqlConnection(SqlPubsConnString)
  614.         cn.Open()
  615.  
  616.         ' Prepare a FOR XML command.
  617.         Dim cmd As New SqlCommand("SELECT pub_name FROM Publishers FOR XML AUTO, ELEMENTS", cn)
  618.         ' Create the XmlReader.
  619.         Dim reader As System.Xml.XmlReader = cmd.ExecuteXmlReader()
  620.         ' Display XML data.
  621.         Do While reader.Read
  622.             txtOut.AppendText(reader.Value & ControlChars.CrLf)
  623.         Loop
  624.         ' Close the XmlReader and the connection.
  625.         reader.Close()
  626.         cn.Close()
  627.     End Sub
  628.  
  629.     ' call a parameterized command
  630.  
  631.     Private Sub btnParamCommand_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnParamCommand.Click
  632.  
  633.         ' Prepare a command on that connection
  634. #If OLEDBBIBLIO Then
  635.         Dim cn As New OleDbConnection(BiblioConnString)
  636.         Dim sql As String = "SELECT * FROM Publishers WHERE PubID=?"
  637.         Dim cmd As New OleDbCommand(sql, cn)
  638.         Dim dr As OleDbDataReader
  639.         Dim fldName As String = "Name"
  640. #ElseIf OLEDBPUBS Then
  641.         Dim cn As New OleDbConnection(OledbPubsConnString )
  642.         Dim sql As String = "SELECT * FROM Publishers WHERE pub_id=?"
  643.         Dim cmd As New OleDbCommand(sql, cn)
  644.         Dim dr as OleDbDataReader 
  645.         Dim fldName as String = "pub_name"
  646. #Else
  647.         Dim cn As New SqlConnection(SqlPubsConnString)
  648.         Dim sql As String = "SELECT * FROM Publishers WHERE PubID=@p1"
  649.         Dim cmd As New SqlCommand(sql, cn)
  650.         dim dr as SqlDataReader 
  651.         Dim fldName as String = "pub_name"
  652. #End If
  653.  
  654.         ' open the connection
  655.         cn.Open()
  656.  
  657.         ' Define the first (and only) parameter and assign its value.
  658.         cmd.Parameters.Add("PubID", 1)
  659.  
  660.         ' Read the result.
  661.         dr = cmd.ExecuteReader()
  662.         ' No need to loop, because we know there is only one row.
  663.         dr.Read()
  664.         txtOut.Text = dr(fldName).ToString & ControlChars.CrLf
  665.         dr.Close()
  666.  
  667.         ' Change the parameter's value and re-execute the query.
  668.         cmd.Parameters(0).Value = 10
  669.         dr = cmd.ExecuteReader
  670.         dr.Read()
  671.         txtOut.AppendText(dr(fldName).ToString & ControlChars.CrLf)
  672.  
  673.         dr.Close()
  674.         cn.Close()
  675.     End Sub
  676.  
  677.     ' call a stored procedure
  678.     ' IMPORTANT: requires that the Pubs database contains a stored proc
  679.     ' named ByRoyalty2 - read book for directions about creating this SP
  680.  
  681.     Private Sub btnStoredProc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStoredProc.Click
  682.         ' This only works with SQL Server
  683.  
  684.         ' This is the name of the stored procedure.
  685.         ' (Note that you must create this procedure, which isn't in PUBS)
  686.         Dim sql As String = "byroyalty2"
  687.  
  688. #If OLEDBBIBLIO Or OLEDBPUBS Then
  689.         Dim cn As New OleDbConnection(OledbPubsConnString)
  690.         Dim cmd As New OleDbCommand(sql, cn)
  691.         Dim dr As OleDbDataReader
  692. #Else
  693.         Dim cn As New SqlConnection(SqlPubsConnString)
  694.         Dim cmd As New SqlCommand(sql, cn)
  695.         dim dr as SqlDataReader 
  696. #End If
  697.         ' Open the connection.
  698.         cn.Open()
  699.  
  700.         cmd.CommandType = CommandType.StoredProcedure
  701.  
  702.         ' Define the return value parameter.
  703.         cmd.Parameters.Add("@numtitles", OleDbType.Integer)
  704.         cmd.Parameters(0).Direction = ParameterDirection.ReturnValue
  705.         ' Define the first (input) parameter and assign its value.
  706.         cmd.Parameters.Add("@percentage", 100)
  707.  
  708.         ' Define the second (output) parameter and set it direction.
  709.         ' (A better method for setting the direction and other properties.)
  710.         With cmd.Parameters.Add("@avgprice", SqlDbType.Float)
  711.             .Direction = ParameterDirection.Output
  712.         End With
  713.  
  714.         ' Read the result.
  715.         dr = cmd.ExecuteReader()
  716.         Do While dr.Read
  717.             txtOut.AppendText(dr(0).ToString & ControlChars.CrLf)
  718.         Loop
  719.         dr.Close()
  720.  
  721.         ' After you close the DataReader you can read the return value and output argument.
  722.         txtOut.AppendText("# of titles = " & cmd.Parameters("@numtitles").Value.ToString & ControlChars.CrLf)
  723.         txtOut.AppendText("Average price = " & cmd.Parameters("@avgprice").Value.ToString)
  724.  
  725.         cn.Close()
  726.     End Sub
  727.  
  728.     ' demonstrate the DeriveParameters method
  729.     ' IMPORTANT: requires that the Pubs database contains a stored proc
  730.     ' named ByRoyalty2 - read book for directions about creating this SP
  731.  
  732.     Private Sub btnDeriveParams_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeriveParams.Click
  733.         ' This only works with SQL Server
  734.  
  735.         ' This is the name of the stored procedure.
  736.         ' (Note that you must create this procedure, which isn't in PUBS)
  737.         Dim sql As String = "byroyalty2"
  738.  
  739. #If OLEDBBIBLIO Or OLEDBPUBS Then
  740.         Dim cn As New OleDbConnection(OledbPubsConnString)
  741.         Dim cmd As New OleDbCommand(sql, cn)
  742.         Dim dr As OleDbDataReader
  743. #Else
  744.         Dim cn As New SqlConnection(SqlPubsConnString)
  745.         Dim cmd As New SqlCommand(sql, cn)
  746.         dim dr as SqlDataReader 
  747. #End If
  748.  
  749.         ' Open the connection.
  750.         cn.Open()
  751.         cmd.CommandType = CommandType.StoredProcedure
  752.  
  753.         ' Populate the Parameters collection with a trip to the server.
  754. #If OLEDBBIBLIO Or OLEDBPUBS Then
  755.         OleDbCommandBuilder.DeriveParameters(cmd)
  756.         Dim par As OleDbParameter
  757. #Else
  758.         SqlCommandBuilder.DeriveParameters(cmd)
  759.         Dim par As SqlParameter
  760. #End If
  761.  
  762.         ' Display parameters found.
  763.         Dim msg As String
  764.         For Each par In cmd.Parameters
  765.             msg &= par.ParameterName & " " & par.DbType.ToString & " (" & par.Direction.ToString & ")" & ControlChars.CrLf
  766.         Next
  767.         MessageBox.Show(msg, "Parameters found", MessageBoxButtons.OK, MessageBoxIcon.Information)
  768.  
  769. #If OLEDBBIBLIO Or OLEDBPUBS Then
  770.         ' adjust param names to comply with sql server names.
  771.         For Each par In cmd.Parameters
  772.             par.ParameterName = "@" & par.ParameterName
  773.         Next
  774. #End If
  775.  
  776.         ' set the value of the (only) input parameter
  777.         cmd.Parameters("@percentage").Value = 100
  778.         'pass a dummy value for the output parameter (incorrectly retrieved as input/output)
  779.         cmd.Parameters("@avgprice").Value = 0
  780.  
  781.         ' Read the result.
  782.         dr = cmd.ExecuteReader()
  783.         Do While dr.Read
  784.             txtOut.AppendText(dr(0).ToString & ControlChars.CrLf)
  785.         Loop
  786.         dr.Close()
  787.  
  788.         ' After you close the DataReader you can read the return value and output argument.
  789.         txtOut.AppendText("# of titles = " & cmd.Parameters("@RETURN_VALUE").Value.ToString & ControlChars.CrLf)
  790.         txtOut.AppendText("Average price = " & cmd.Parameters("@avgprice").Value.ToString)
  791.  
  792.         cn.Close()
  793.     End Sub
  794.  
  795.     ' read multiple resultsets (SQL Server only)
  796.  
  797.     Private Sub btnMultipleResultsets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMultipleResultsets.Click
  798.         Dim sql As String = "SELECT pub_name FROM Publishers;SELECT Title FROM titles;"
  799.  
  800.         ' Open a connection to Pubs databse on SQL Server .
  801. #If OLEDBBIBLIO Or OLEDBPUBS Then
  802.         Dim cn As New OleDbConnection(OledbPubsConnString)
  803.         Dim cmd As New OleDbCommand(sql, cn)
  804.         Dim dr As OleDbDataReader
  805. #Else
  806.         Dim cn As New SqlConnection(SqlPubsConnString)
  807.         Dim cmd As New SqlCommand(sql, cn)
  808.         dim dr as SqlDataReader 
  809. #End If
  810.  
  811.         cn.Open()
  812.  
  813.         ' Define an SQL statement with multiple queries.
  814.         dr = cmd.ExecuteReader()
  815.         Dim resCount As Integer
  816.  
  817.         Do
  818.             resCount += 1
  819.             txtOut.AppendText("RESULTSET #" & resCount.ToString)
  820.             txtOut.AppendText(ControlChars.CrLf)
  821.  
  822.             Do While dr.Read
  823.                 txtOut.AppendText(dr(0).ToString)
  824.                 txtOut.AppendText(ControlChars.CrLf)
  825.             Loop
  826.             txtOut.AppendText(ControlChars.CrLf)
  827.         Loop While dr.NextResult
  828.         dr.Close()
  829.         cn.Close()
  830.     End Sub
  831.  
  832. End Class
  833.